import localForage from 'localforage'
import { useKnifeStore } from '@/store'
import NProgress from 'nprogress'
// import { generateApiGroup, generateDocRoute } from '@/utils/knife4j'
import type { Router } from 'vue-router'
import { setRouteEmitter } from '@/utils/route-listener'
import { AuthRoute, ModelsRoute, NotFoundRoute } from '../constants'

function setupDefaultRouter(router: Router) {
  router.addRoute('Root', ModelsRoute)
  router.addRoute('Root', AuthRoute)
  router.addRoute('Root', NotFoundRoute)
}

function setupPageGuard(router: Router) {
  router.beforeEach(async (to) => {
    // emit route change
    setRouteEmitter(to)
  })
}

/**
 * 添加动态路由
 *
 * @param router
 */
function setupDynamicRoute(router: Router) {
  let asyncRouterRefresh = true // 作为next第二次跳转是否再次请求的标识
  router.beforeEach(async (to, from, next) => {
    NProgress.start()
    const knifeStore = useKnifeStore()
    const knifeRefresh = knifeStore.documentResource && knifeStore.documentResource.length === 0

    if ((from?.path === '/' && asyncRouterRefresh) || knifeRefresh) {
      // 刷新页面，清空组和接口列表储存
      localForage.removeItem('knifeGlobalResourceCache')
      await knifeStore.initKnife4j({})
      // const tmpDocumentResource = JSON.parse(JSON.stringify(knifeStore.documentResource))
      // const docRoutes = generateDocRoute(tmpDocumentResource)
      // const docRoutes2 = generateApiGroup(tmpDocumentResource)
      // console.log('docRoutes', docRoutes2)
      // docRoutes.push(NotFoundRoute)
      // docRoutes.forEach((item) => {
      //   router.addRoute('Root', item)
      // })
      if (to.matched.length === 0) {
        asyncRouterRefresh = false
        next({ ...to, path: decodeURI(to.fullPath), replace: true })
      } else {
        next()
      }
    } else {
      next()
    }
    // else if (asyncRouterRefresh) {
    //   console.log('2', 2)
    //   const tmpDocumentResource = JSON.parse(JSON.stringify(knifeStore.documentResource))
    //   const docRoutes = generateDocRoute(tmpDocumentResource)
    //   console.log('docRoutes', docRoutes)
    //   docRoutes.push(NotFoundRoute)
    //   docRoutes.forEach((item) => {
    //     router.addRoute('Root', item)
    //   })
    //   asyncRouterRefresh = to.matched.length === 0
    //   next({ ...to, replace: true })
    // }

    NProgress.done()
  })
}

export default function createRouteGuard(router: Router) {
  setupDefaultRouter(router)
  setupDynamicRoute(router)
  setupPageGuard(router)
}
